package com.link2room.aeriabots.controller.wxReception;

import com.link2room.aeriabots.constant.WXConstant;
import com.link2room.aeriabots.dto.param.base.WxComponentParamDto;
import com.link2room.aeriabots.facade.IWXComponentFacadeService;
import com.link2room.common.util.HttpUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by LN on 2016/9/1.
 */
@RestController
@RequestMapping("/notify/VerifyTickets")
public class WxVerifyNotifyController {
    @Resource
    private IWXComponentFacadeService wxComponentFacadeService;
    @RequestMapping(method= RequestMethod.POST)
    public void ticket(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        try {
            WxComponentParamDto verifyTicketDto = new WxComponentParamDto();
            String msgSignature = request.getParameter("msg_signature");
            String nonce =request.getParameter("nonce");
            String timeStamp =request.getParameter("timestamp");
            String body = HttpUtil.getRequestBody(request);
            verifyTicketDto.setMsgSignature(msgSignature);
            verifyTicketDto.setNonce(nonce);
            verifyTicketDto.setTimeStamp(timeStamp);
            verifyTicketDto.setBody(body);
            verifyTicketDto.setLhotelGroupCode("WX");
            /** `
             * 存放verifyTicket
             */
            wxComponentFacadeService.setVerifyTicket(verifyTicketDto);
            /**
             * 更新ComponentAccessToken
             */
            wxComponentFacadeService.updateComponentAccessToken();
            /**
            * 三方公众号授权凭证
             * 更新jspticket
            * 更新authorizationToken
            */
            wxComponentFacadeService.refreshAuthorizerToken();
        }catch (Exception e){
        }finally {
            returnSuccess(response);
        }
    }

    private void returnSuccess(HttpServletResponse response) throws IOException {
        PrintWriter write = response.getWriter();
        write.write("success");
        write.flush();
        write.close();
    }

    @RequestMapping(method= RequestMethod.GET)
    public void printTicket(HttpServletResponse response) throws Exception{
        PrintWriter write = response.getWriter();
        write.write(WXConstant.Component.getVerifyTicket()+" "+WXConstant.Component.getDate());
        write.flush();
        write.close();
    }
}
